//
//  GameIAP.m
//  ProjectL
//
//  Created by Nguyen Tan Loc on 12/8/13.
//  Copyright (c) 2013 Nguyen Tan Loc. All rights reserved.
//

#import "Reachability.h"
#import "Utility.h"
#import "GameIAP.h"
#import "UserInfo.h"
#import "ItemInfo.h"
#import "VerificationController.h"

@implementation GameIAP

+(GameIAP *) getInstance
{
    static GameIAP *mInstance;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        NSArray *listProductIdentifiers = [[NSArray alloc ] initWithObjects:
                                           IDENTIFIER_GOLD_PACKET_TINY,
                                           IDENTIFIER_GOLD_PACKET_SMALL,
                                           IDENTIFIER_GOLD_PACKET_MEDIUM,
                                           IDENTIFIER_GOLD_PACKET_LARGE,
                                          nil];
        mInstance = [[GameIAP alloc] initWithProductIdentifiers:listProductIdentifiers];
    });
    
    return mInstance;
}

-(id) initWithProductIdentifiers:(NSArray *)identifiers
{
    if (self = [super initWithProductIdentifiers:identifiers])
    {

    }
    
    return self;
}

-(void) buyPacket:(IAP_TYPE)type
{
    if ([self checkInternetConnection])
    {
        CCLOG(@"connected");
        [self createIndicatorAndAlphaLayer];
    }
    else
    {
        CCLOG(@"not connect");
        [self showAlearConnectionFail];
        return;
    }
    
    switch (type) {
        case eIAP_TINY:
            [self buyProduct:IDENTIFIER_GOLD_PACKET_TINY];
            break;
            
        case eIAP_SMALL:
            [self buyProduct:IDENTIFIER_GOLD_PACKET_SMALL];
            break;
            
        case eIAP_MEDIUM:
            [self buyProduct:IDENTIFIER_GOLD_PACKET_MEDIUM];
            break;
            
        case eIAP_LARGE:
            [self buyProduct:IDENTIFIER_GOLD_PACKET_LARGE];
            break;
            
        default:
            break;
    }
}

-(void) createIndicatorAndAlphaLayer
{
    if (mIndicator == nil)
    {
        CGSize winSize = [[CCDirector sharedDirector] winSize];
        mIndicator = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhite];
        [mIndicator setFrame:CGRectMake(winSize.width / 2 - 8, winSize.height / 2 - 8, 8, 8)];

        mAlphalayer = [[AlphaLayer alloc] init];
    }
    
    [[[CCDirector sharedDirector] runningScene] addChild:mAlphalayer z:1000 tag:1000];
    [[[CCDirector sharedDirector] view] addSubview:mIndicator];
    [mIndicator startAnimating];
}

-(void) removeIndicatorAndAlphaLayer
{
    [mAlphalayer removeFromParent];
    
    [mIndicator stopAnimating];
    [mIndicator removeFromSuperview];
}

- (BOOL)checkInternetConnection
{
    Reachability *reachability = [Reachability reachabilityForInternetConnection];
    NetworkStatus networkStatus = [reachability currentReachabilityStatus];
    return !(networkStatus == NotReachable);
}

-(void) showAlearConnectionFail
{
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Connection fail!"
                                                    message:@"Please check your network connection"
                                                   delegate:self
                                          cancelButtonTitle:@"OK"
                                          otherButtonTitles:nil, nil];
    [[[CCDirector sharedDirector] view] addSubview:alert];
    [alert show];
    [alert release];
}

-(void) addGoldToUser
{
    [self removeIndicatorAndAlphaLayer];
    
    if ([mCurrentTransaction.payment.productIdentifier isEqual:IDENTIFIER_GOLD_PACKET_TINY])
    {
        CCLOG(@"buy tiny pack");
        [UserInfo getInstance]._userGold += [[ItemInfo getInstance] getPacketNum:eIAP_TINY];
    }
    else if ([mCurrentTransaction.payment.productIdentifier isEqual:IDENTIFIER_GOLD_PACKET_SMALL])
    {
        CCLOG(@"buy small pack");
        [UserInfo getInstance]._userGold += [[ItemInfo getInstance] getPacketNum:eIAP_SMALL];
    }
    else if ([mCurrentTransaction.payment.productIdentifier isEqual:IDENTIFIER_GOLD_PACKET_MEDIUM])
    {
        CCLOG(@"buy medium pack");
        [UserInfo getInstance]._userGold += [[ItemInfo getInstance] getPacketNum:eIAP_MEDIUM];
    }
    else if ([mCurrentTransaction.payment.productIdentifier isEqual:IDENTIFIER_GOLD_PACKET_LARGE])
    {
        CCLOG(@"buy large pack");
        [UserInfo getInstance]._userGold += [[ItemInfo getInstance] getPacketNum:eIAP_LARGE];
    }
    
    [[UserInfo getInstance] saveUserInfo];
    [[NSNotificationCenter defaultCenter] postNotificationName:EVENT_GOLD_CHANGED object:nil];
    
    [mCurrentTransaction release];
    mCurrentTransaction = nil;
}

-(void) completeTransaction:(SKPaymentTransaction *)transaction
{
    mCurrentTransaction = [transaction retain];
    [[VerificationController sharedInstance] verifyPurchase:transaction completionHandler:^(BOOL success) {
        [self addGoldToUser];
    }];
    [super completeTransaction:transaction];
}

-(void) restoreTransaction:(SKPaymentTransaction *)transaction
{
    [super restoreTransaction:transaction];
    [self removeIndicatorAndAlphaLayer];
}

-(void) failedTransaction:(SKPaymentTransaction *)transaction
{
    [super restoreTransaction:transaction];
    [self removeIndicatorAndAlphaLayer];
}

@end
